/**
 @author: zhulizhe
 @date: 2020-04-18 18:17:25
 @Email：345841634@qq.com
 @url：https://github.com/lovecrossyou
 */
import React, {useState, useEffect} from 'react';
import {
    Text,
    View,
    StyleSheet,
    ScrollView,
    TouchableOpacity, NativeModules,
} from 'react-native';
import {scaleSizeW, scaleSizeH, setSpText} from '@/util/screen';
import wifiStore from '@/store/wifi';
import {useLocalStore, useObserver} from 'mobx-react';
import Prompt from 'react-native-modal-prompt';

const WifiMgr = NativeModules.WifiMgr;
import Toast from 'react-native-tiny-toast';
import NetInfo from '@react-native-community/netinfo';

const WifiList = ({navigation}) => {
    const wifiInfo = useLocalStore(() => ({device: {}}));
    const [promptVisible, setVisible] = useState(false);
    if (!wifiStore) {
        return null;
    }

    const connect = device => {
        wifiInfo.device = device;
        setVisible(true);
    };
    const connectWifi = password => {
        if (wifiInfo.device.SSID) {
            const ssid = wifiInfo.device.SSID;
            wifiStore.connnect(ssid, password);
        }
    };

    // 检测网络状态
    const checkNetState = () => {
        WifiMgr.connectionStatus((connected) => {
            if (connected === true) {
                navigation.replace('Main');
                Toast.show('connected');
            } else {
                Toast.show('disconnected');
            }
        });
    };

    useEffect(() => {
        checkNetState();
        wifiStore.loadWifiList();

        //监听网络变化事件
        const unsubscribe = NetInfo.addEventListener(state => {
            if (state.isConnected) {
                navigation.goBack();
            }
        });
        return () => {
            unsubscribe();
        };
    }, []);
    return useObserver(() => (
        <ScrollView contentContainerStyle={styles.container}>
            <View style={styles.header}>
                <View>
                    <Text style={styles.title}>Connect to WIFI</Text>
                </View>
                <View>
                    <Text style={styles.desc}>
                        Follow the steps in the app to connect the mirror
                        to your home WIFI network.
                    </Text>
                </View>
            </View>
            {wifiStore.list.map((d, index) => (
                <TouchableOpacity onPress={() => connect(d)} key={`${index}#`}>
                    <View style={styles.item}>
                        <View style={styles.name_box}>
                            <Text style={styles.name}>{d.SSID}</Text>
                            {/*<Text style={styles.status}>{d.level}</Text>*/}
                        </View>
                        {/*<Text style={styles.id}>{d.BSSID}</Text>*/}
                    </View>
                </TouchableOpacity>
            ))}
            <Prompt
                visible={promptVisible}
                title={`Connect to ${wifiInfo.device.SSID}`}
                placeholder="wifi password"
                defaultValue=""
                operation={[
                    {
                        text: 'Cancel',
                        color: '#000',
                        onPress: () => {
                            setVisible(false);
                        },
                    },
                    {
                        text: 'Ok',
                        onPress: value =>
                            new Promise(resolve => {
                                console.log(`the prompt value is ${value}`);
                                connectWifi(value);
                                setVisible(false);
                            }),
                    },
                ]}
            />
        </ScrollView>
    ));
};
const styles = StyleSheet.create({
    container: {
        width: '100%',
    },
    header: {
        paddingHorizontal: scaleSizeW(20),
        backgroundColor: '#e1e1e1',

    },
    title: {
        paddingVertical: scaleSizeH(20),
        fontWeight: 'bold',
        fontSize: setSpText(60),
    },
    desc: {
        paddingVertical: scaleSizeH(10),
        color: '#999',
    },
    item: {
        width: '100%',
        paddingVertical: scaleSizeH(30),
        paddingHorizontal: scaleSizeW(20),
        backgroundColor: '#fff',
        borderBottomWidth: scaleSizeH(1),
        borderBottomColor: '#f9f9f9',
    },
    name_box: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    status: {
        color: '#cc2636',
        fontSize: setSpText(20),
        fontWeight: 'bold',
    },
    name: {
        color: '#333',
        fontSize: setSpText(32),
        fontWeight: 'bold',
        marginBottom: scaleSizeH(8),
        marginRight: scaleSizeW(10),
    },

    id: {
        color: '#999',
        fontSize: setSpText(24),
    },
});
export default WifiList;
